<template>
  <div class="dashboard-container">
    <el-card 
      class="box-card" 
      v-loading="loading"
    >
      <!-- 表单输入框 -->
      <el-form 
        ref="form" 
        :model="form" 
        label-width="80px" 
        :inline="true"
      >
        <el-form-item label="关键字">
          <el-input 
            v-model="form.keyword" 
            placeholder="根据文章标题搜索"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select 
            v-model="form.state" 
            placeholder="请选择"
          >
            <el-option 
              label="启用" 
              value="1"
            ></el-option>
            <el-option 
              label="禁用" 
              value="0"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 搜索/清除按钮 -->
        <el-button
          class="remove-btn"
          @click="onRemoveAll"
        >
          清除
        </el-button>
        <el-button
          type="primary"
          @click="onSearchArticlesList"
        >
          搜索
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-edit"
          class="addUser"
          @click="onAddArticlesList"
        >
          新增技巧
        </el-button>
      </el-form>
      <!-- 新增/修改 文章 -->
      <el-dialog 
        :title="notice.title ? '修改文章' : '新增文章'" 
        :visible.sync="addVisible" 
        width="60%"  
        v-loading="loading"
      >
        <el-form 
          :model="notice" 
          label-width="100px" 
          :rules="rules" 
          class="demo-ruleForm"
        >
          <el-form-item 
            label="文章标题" 
            prop="title"
          >
            <el-input 
              v-model="notice.title" 
              auto-complete="off" 
              placeholder="请输入文章标题"
            >
            </el-input>
          </el-form-item>
          <el-form-item 
            label="文章内容" 
            prop="content"
          >
          <quill-editor
            v-model="notice.articleBody"
            ref="myQuillEditor"
            :options="editorOption"
          >
          </quill-editor>
          </el-form-item>
          <el-form-item label="视频地址" >
            <el-input 
              v-model="notice.videoURL" 
              auto-complete="off" 
              placeholder="请输入视频地址"
            >
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addVisible = false">取 消</el-button>
          <el-button 
            type="primary" 
            @click="addArticles(notice)"
          >
            确 定
          </el-button>
        </div>
      </el-dialog>
      <!-- 提示 -->
      <el-alert
        :closable="false"
        :title="`共${articlesList.counts}条纪录`"
        type="info"
        class="hint"
        show-icon>
      </el-alert>
      <!-- 表格 -->
      <my-table
        class="container"
        :table-props="{
          data: articlesList.items,
          border: true
        }"
        :columns="[
          { label: '序号', prop: 'index', width: 180, align: 'center' },
          { label: '文章标题', slotName: 'icon', width: 180, align: 'center'},
          { label: '阅读数', prop: 'visits', width: 180, align: 'center' },
          { label: '录入人', prop: 'username', width: 180, align: 'center' },
          { label: '录入时间', prop: 'createTime', width: 180, align: 'center' },
          { label: '状态', prop: 'state', width: 180, width: 180, align: 'center'},
          { label: '操作', width: 180, align: 'center', slotName: 'handle', width: 300, fixed: 'right'},
        ]"

        :pagination-props="{
          layout: 'sizes, prev, pager, next, jumper',
          total: articlesList.counts,
          currentPage: page,
          pageSize: pageSize,
          pageSizes: [10, 20, 30, 40],
        }"
        :pagination-events="{
          'current-change': onCurrentPageChange,
          'size-change': onPageSizeChange
        }"
      >
      <template v-slot:handle="scope" >
        <el-button 
          type="text" 
          @click="onpreviewArticles(scope.row.id)"
        >
          预览
        </el-button>
        <el-button 
          type="text" 
          @click="onVisible(scope.row)"
        >
          {{scope.row.state === '启用' ? '禁用' : '启用'}}
        </el-button>
        <el-button 
          type="text" 
          :disabled="scope.row.state === '启用'" 
          @click="onAddArticlesList(scope.row.id)"
        >
          修改
        </el-button>
        <el-button 
          type="text" 
          :disabled="scope.row.state === '启用'" 
          @click="onRemove(scope.row.id)"
        >
          删除
        </el-button>
      </template>
      <template v-slot:icon="scope">
        <span>{{scope.row.title}}</span>
        <i class="el-icon-film" v-show="scope.row.videoURL"></i>
      </template>
      </my-table>
      <!-- 预览文章 -->
      <el-dialog
        title="预览文章"
        :visible.sync="previewVisible"
        width="400"
      >
        <h2>{{preview.title}}</h2>
        <div class="articleInfo">
          <span>{{ preview.createTime.substring(0, 19).replace('T', ' ')}}</span>
          <span> 超级管理员</span>
          <i class="el-icon-view"></i>
          <span>{{preview.visits}}</span>
        </div>
        <div 
          v-html="preview.articleBody" 
          class="articleContent"
        >
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>

let currentId = null
import { mapActions, mapState } from 'vuex'
import * as articlesApi from '../../api/hmmm/articles'
export default {
  name: 'ArticlesList',
  data () {
    return {
      loading: false,
      form: {
        keyword: '',
        state: ''
      },
      notice: {
        title: '',
        articleBody: '',
        videoURL: ''
      },
      page: 1,
      pageSize: 10,
      addVisible: false,
      previewVisible: false,
      preview: {
        title: '',
        createTime: '',
        username: '',
        visits: '',
        articleBody: ''
      },
      editorOption: {
        modules: {
          toolbar: {container:[
          ['bold', 'italic', 'underline', 'strike'],
          ['blockquote', 'code-block'],
          [{ 'list': 'ordered' }, { 'list': 'bullet' }],
          ['link', 'image']
          ],
          handlers: {
            'image': function(value) {
              if (value) {
                  document.querySelector('.edit-uploader input').click()
              } else {
                  this.quill.format('image', false);
              }
              // this.$refs.aUpload.click() //自定义图片上传回调
            }
          }
          },
          syntax: {
            highlight: text => hljs.highlightAuto(text).value
          }
        }
      },
      rules: {
        title: [
            { required: true, message: '请输入文章标题', trigger: 'blur' },
        ],
        content: [
            { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
      }
    }
  },
  computed: {
    ...mapState('articles', ['articlesList', 'articlesDetail']),
  },
  methods: {
    ...mapActions('articles', ['updateArticlesList', 'updateArticlesDetail']),
    // 点击下一页
    onCurrentPageChange(val) {
      this.page = val
      this.updateArticlesList({
        // ...this.form,
        page: this.page,
        pagesize: this.pageSize
      })
    },
    onPageSizeChange(val) {
      this.page = 1
      this.pageSize = val
      this.updateArticlesList({
        //  ...this.form,
        page: this.page,
        pagesize: this.pageSize
      })
    },
    // 清除按钮
    onRemoveAll() {
      this.form = {
        keyword: '',
        state: ''
      }
    },
    // 搜索按钮
    onSearchArticlesList() {
      this.updateArticlesList({
        ...this.form,
        page: this.page,
        pagesize: this.pageSize
      })
    },
    // 禁用/启用
    async onVisible(scope) {
      await articlesApi.changeState({
        id: scope.id,
        state: scope.state === '禁用' ? 1 : 0
      })
        .then(data => (this.$message.success('操作成功')))
        .catch(err => this.$message.error('操作失败'))
      this.updateArticlesList({ page: this.page, pagesize: this.pageSize })
    },
    // 删除按钮
    onRemove(id) {
      this.$confirm('此操作将永久删除该文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await articlesApi.removeArticles({id})
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.updateArticlesList({ page: this.page, pagesize: this.pageSize })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 点击新增/修改按钮
    async onAddArticlesList(id) {
      if(!isNaN(id)) {
        currentId = id
        await this.updateArticlesDetail({id})
        this.addVisible = true
        this.notice.title = this.articlesDetail.data.title
        this.notice.articleBody = this.articlesDetail.data.articleBody
        this.notice.videoURL = this.articlesDetail.data.videoURL
      }else{
        this.notice.title = ''
        this.notice.articleBody = ''
        this.notice.videoURL = ''
        this.addVisible = true
        currentId = ''
      }

    },
     // 富文本编辑方法
    beforeEditorUpload() {
      // 显示loading动画
      this.quillUpdateImg = true
    },

    editorUploadSuccess(res, file) {
      // 获取富文本组件实例
      let quill = this.$refs.myQuillEditor.quill
      // 如果上传成功
      if (res.code === 0) {
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片  res.info为服务器返回的图片地址
        quill.insertEmbed(length, 'image', res.data.filepath)
        // 调整光标到最后
        quill.setSelection(length + 1)
      } else {
        this.$message.error('图片插入失败')
      }
      // loading动画消失
      this.quillUpdateImg = false
    },
    // 富文本图片上传失败
    editorUploadError() {
      // loading动画消失
      this.quillUpdateImg = false
      this.$message.error('图片插入失败')
    },
    // 点击确定新增/修改
    async addArticles(notice) {
      this.loading = true
      if(currentId) {
        await articlesApi.updateArticles({
          ...notice,
          id: currentId
        })
          .then(res => this.$message.success('操作成功'))
          .catch(err => this.$message.error('操作失败'))
      }else{
          await articlesApi.addArticles({
          ...notice,
          id: ' '
      })
        .then(res => this.$message.success('操作成功'))
        .catch(err => this.$message.error('操作失败'))
      }
       this.loading = false
      this.addVisible = false
      this.updateArticlesList({ page: this.page, pagesize: this.pageSize })
    },
    // 预览文章
    async onpreviewArticles(id) {
      await this.updateArticlesDetail({id})
      this.previewVisible = true
      this.preview.title = this.articlesDetail.data.title
      this.preview.createTime = this.articlesDetail.data.createTime
      this.preview.username = this.articlesDetail.data.username
      this.preview.visits = this.articlesDetail.data.visits
      this.preview.articleBody = this.articlesDetail.data.articleBody
    }
  },
  async created() {
    this.loading = true
    await this.updateArticlesList({ page: this.page, pagesize: this.pageSize })
    this.loading = false
  }
}
</script>

<style lang="scss" scoped>

.dashboard-container {
  padding: 16px;

  .remove-btn {
    margin-left: 18px;
  }

  .el-icon-film {
    color: #0000f5;
  }

  .addUser {
    float: right;
    background-color: #7ebf50;
    border: none;
  }

  ::v-deep .ql-editor {
    height: 300px;
  }
  ::v-deep img {
    width: 100%;
  }

  .el-icon-view {
    margin: 0 5px;
  }
  .articleInfo{
    padding: 0 16px;
  }
  .hint {
    margin-bottom: 10px;
  }
  .articleContent {
    border-top: 1px dashed #ccc;
    margin-top: 5px;
    background-color: #f5f5f5;
    padding: 0 16px;
  }
}
</style>
